﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using QXBook.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;
using QXBook.Utils;
using System.Data.Common;

namespace QXBook.Service
{
    /// <summary>
    /// 方法基类
    /// </summary>
    public class ServiceBase
    {
        protected Database db
        {
            get
            {
                if (_db == null)
                {
                    _db = DatabaseFactory.CreateDatabase("ApplicationServices");
                }
                return _db;
            }
        }
        private static Database _db = null;

        /// <summary>
        /// 从记录集中返回实体
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<IModelBase> GetEntitysObjectFromTable(DataTable dt, Type type)
        {
            if (dt == null) return null;
            if (dt.Rows.Count == 0) return null;
            List<IModelBase> list = new List<IModelBase>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow Row = dt.Rows[i];
                IModelBase entity = this.GetEntityObjectFromRow(Row, type);
                list.Add(entity);
            }
            return list;
        }

        /// <summary>
        /// 从记录行中得到实体
        /// </summary>
        /// <param name="?"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public IModelBase GetEntityObjectFromRow(DataRow row, Type type)
        {
            if (row == null) return null;
            switch (type.ToString())
            {
                case "QXBook.Model.Categories":
                    CategoryInfo categories = new CategoryInfo();
                    categories.CategoryID = (int)row["CategoryID"];
                    categories.CategoryName = row["iOrder"].ToString();
                    categories.ParentID = (int)row["ParentID"];
                    categories.ParentIDList = row["ParentIDList"].ToString();
                    categories.OrderKey = row["OrderKey"].ToString().Trim();
                    categories.PartType = (Part)(int)row["PartType"];
                    categories.AddDate = (DateTime)row["dUpdateDate"];
                    return (IModelBase)categories;
                case "QXBook.Model.Resources":
                    ResourcesInfo resources = new ResourcesInfo();
                    resources.ResourceID = (int)row["ResourceID"];
                    resources.ArticleID = (int)row["ArticleID"];
                    resources.ResourceName = row["ResourceName"].ToString();
                    resources.ResourcePath = row["ResourcePath"].ToString();
                    resources.Downs = (int)row["Downs"];
                    return (IModelBase)resources;
                case "QXBook.Model.ArticleTemplateInfo":
                    ArticleTemplateInfo template = new ArticleTemplateInfo();
                    template.ID = (int)row["Id"];
                    template.TemplateName = row["TemplateName"].ToString();
                    return (IModelBase)template;
                case "TCG.Entity.FeedBackInfo":
                    FeedBackInfo feedBack = new FeedBackInfo();
                    feedBack.FeedBackID = (int)row["FeedBackID"];
                    feedBack.UserID = (int)row["UserID"];
                    feedBack.UserName = row["UserName"].ToString();
                    feedBack.Tel = row["Tel"].ToString();
                    feedBack.QQ = row["QQ"].ToString();
                    feedBack.Ip = row["Ip"].ToString();
                    feedBack.Email = row["Email"].ToString();
                    feedBack.Title = row["Title"].ToString();
                    feedBack.Content = row["Content"].ToString();
                    feedBack.RelatedID = (int)row["RelatedID"];
                    feedBack.AddDate = CommonUtils.ToTime(row["AddDate"].ToString());
                    return (IModelBase)feedBack;
            }
            return null;
        }

        public string GetJsEntitys(Dictionary<string, IModelBase> entitys, Type type)
        {

            if (type == null) return null;
            StringBuilder sb = new StringBuilder();
            sb.Append("var _" + type.ToString().Split('.')[2] + "=[");

            if (entitys != null)
            {
                int i = 0;
                foreach (KeyValuePair<string, IModelBase> keyvalue in entitys)
                {
                    //sb.Append(this.GetJsEntity(keyvalue.Value, type));
                    i++;
                    if (i != entitys.Count) sb.Append(",");
                }
            }
            sb.Append("];");
            return sb.ToString();
        }

        /// <summary>
        /// 得到实体的JSON对象
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        //public string GetJsEntity(EntityBase entity, Type type)
        //{
        //    if (entity == null) return "{}";
        //    if (type == null) return "{}";
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("{");
        //    switch (type.ToString())
        //    {
        //        case "TCG.Entity.Categories":
        //            Categories categories = (Categories)entity;
        //            sb.Append("Id:\"" + categories.Id + "\",");
        //            sb.Append("ResourceListTemplate:" + this.GetJsEntity((EntityBase)categories.ResourceListTemplate, typeof(Template)) + ",");
        //            sb.Append("iOrder:" + categories.iOrder.ToString() + ",");
        //            sb.Append("ParentId:\"" + categories.Parent + "\",");
        //            sb.Append("ResourceTemplate:" + this.GetJsEntity((EntityBase)categories.ResourceTemplate, typeof(Template)) + ",");
        //            sb.Append("Directory:\"" + categories.vcDirectory + "\",");
        //            sb.Append("Url:\"" + categories.vcUrl + "\",");
        //            sb.Append("UpdateDate:\"" + categories.dUpdateDate.ToString() + "\",");
        //            sb.Append("Visible:\"" + categories.cVisible + "\",");
        //            sb.Append("DataBaseService:\"" + categories.DataBaseService + "\",");
        //            sb.Append("Name:\"" + categories.vcName + "\",");
        //            sb.Append("Skin:" + this.GetJsEntity((EntityBase)categories.SkinInfo, typeof(Skin)) + ",");
        //            sb.Append("ClassName:\"" + categories.vcClassName + "\"");
        //            break;
        //        case "TCG.Entity.Template":
        //            Template template = (Template)entity;
        //            sb.Append("Id:\"" + template.Id + "\",");
        //            sb.Append("SkinId:\"" + template.SkinInfo + "\",");
        //            sb.Append("TemplateType:" + ((int)template.TemplateType).ToString() + ",");
        //            sb.Append("ParentId:\"" + template.iParentId + "\",");
        //            sb.Append("SystemType:" + template.iSystemType.ToString() + ",");
        //            sb.Append("TempName:\"" + template.vcTempName + "\",");
        //            sb.Append("Url:\"" + template.vcUrl + "\"");
        //            break;
        //        case "TCG.Entity.Skin":
        //            Skin skin = (Skin)entity;
        //            sb.Append("Id:\"" + skin.Id + "\",");
        //            sb.Append("Name:\"" + skin.Name + "\",");
        //            sb.Append("Pic:\"" + skin.Pic + "\",");
        //            sb.Append("WebDescription:\"" + skin.WebDescription + "\",");
        //            sb.Append("IndexPage:\"" + skin.IndexPage + "\",");
        //            sb.Append("WebKeyWords:\"" + skin.WebKeyWords + "\"");
        //            break;
        //        case "TCG.Entity.FileCategories":
        //            FileCategories filecategories = (FileCategories)entity;
        //            sb.Append("Id:" + filecategories.Id + ",");
        //            sb.Append("iParentId:" + filecategories.iParentId.ToString() + ",");
        //            sb.Append("vcFileName:\"" + filecategories.vcFileName + "\"");
        //            break;
        //        case "TCG.Entity.Properties":
        //            Properties categorieProperties = (Properties)entity;
        //            sb.Append("Id:" + categorieProperties.Id + ",");
        //            sb.Append("PropertiesCategorieId:" + categorieProperties.PropertiesCategorieId + ",");
        //            sb.Append("ProertieName:\"" + categorieProperties.ProertieName + "\",");
        //            sb.Append("Type:\"" + categorieProperties.Type + "\",");
        //            sb.Append("Values:\"" + categorieProperties.Values + "\",");
        //            sb.Append("width:" + categorieProperties.width + ",");
        //            sb.Append("height:" + categorieProperties.height + ",");
        //            sb.Append("iOrder:" + categorieProperties.iOrder + "");
        //            break;

        //        case "TCG.Entity.ResourceProperties":
        //            ResourceProperties rategorieProperties = (ResourceProperties)entity;
        //            sb.Append("Id:" + rategorieProperties.Id + ",");
        //            sb.Append("ResourceId:\"" + rategorieProperties.ResourceId + "\",");
        //            sb.Append("PropertieName:\"" + rategorieProperties.PropertieName + "\",");
        //            sb.Append("PropertieValue:\"" + objectHandlers.JSEncode( rategorieProperties.PropertieValue) + "\",");
        //            sb.Append("PropertieId:" + rategorieProperties.PropertieId + ",");
        //            sb.Append("iOrder:" + rategorieProperties.iOrder + "");
        //            break;

        //        case "TCG.Entity.Speciality":
        //            Speciality speciality = (Speciality)entity;
        //            sb.Append("Id:" + speciality.Id + ",");
        //            sb.Append("iParent:" + speciality.iParent + ",");
        //            sb.Append("SkinId:'" + speciality.SkinId + "',");
        //            sb.Append("vcTitle:'" + speciality.vcTitle + "'");
        //            break;

        //        case "TCG.Entity.Resources":
        //            Resources resources = (Resources)entity;
        //            sb.Append("Id:" + resources.Id + ",");
        //            sb.Append("vcTitle:'" + resources.vcTitle + "',");
        //            sb.Append("vcSmallImg:'" + resources.vcSmallImg + "',");
        //            sb.Append("vcFilePath:'" + resources.vcFilePath + "',");
        //            sb.Append("dAddDate:'" + resources.dAddDate + "'");
        //            break;

        //    }
        //    sb.Append("}");
        //    return sb.ToString();
        //}

        /// <summary>
        /// 通用分页方法
        /// </summary>
        /// <param name="ps"></param>
        /// <param name="tablesql"></param>
        /// <param name="strOrder"></param>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public DataTable GetListPager(ref PagerState ps, string tablesql, string strKey, DbCommand cmd)
        {
            if (ps.CurrentPage < 1) ps.CurrentPage = 1;
            if (ps.PageSize < 1) ps.PageSize = 10;

            string myVw = string.Format(" ({0}) tempVw ", tablesql);
            string sqlRowCount = string.Format(" select count(0) as recordCount from {0}", myVw);

            cmd.CommandText = sqlRowCount;
            ps.RecordCount = Convert.ToInt32(this.db.ExecuteScalar(cmd));

            if ((ps.RecordCount % ps.PageSize) > 0)
                ps.PageCount = ps.RecordCount / ps.PageSize + 1;
            else
                ps.PageCount = ps.RecordCount / ps.PageSize;

            string sqlview =string.Empty;
            if (ps.CurrentPage == 1)//第一页
            {
                sqlview = string.Format("select top {0} * FROM ({1}) AS TMP1 order by {2}", ps.PageSize, tablesql, string.IsNullOrEmpty(ps.OrderByColumn) ? strKey : ps.OrderByColumn);
            }
            else 
            {
                int pageBound = (ps.PageSize * (ps.CurrentPage - 1));
                if (ps.CurrentPage > ps.PageCount)
                {
                    pageBound = (ps.PageSize * (ps.PageCount - 1));
                }

                sqlview = string.Format("select top {0} * FROM ({1}) AS TMP1 WHERE {2} > (select max({2}) FROM (SELECT TOP {3} {2} FROM ({1}) order by {2}) AS TMP2) order by {4}", ps.PageSize, tablesql, strKey, pageBound, ps.OrderByColumn);
            }

            cmd.CommandText = sqlview;

            DataSet ds = this.db.ExecuteDataSet(cmd);
            if (ds != null && ds.Tables.Count > 0)
                return ds.Tables[0];
            return null;
        }
    }
}
